define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'scanwork/product/index' + location.search,
                    add_url: 'scanwork/product/add',
                    edit_url: 'scanwork/product/edit',
                    del_url: 'scanwork/product/del',
                    multi_url: 'scanwork/product/multi',
                    table: 'product',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true},
                        {field: 'name', title: __('产品名称'), align: 'left'},
                        {field: 'specification', title: __('产品规格'), align: 'left'},
                        {field: 'remark', title: __('备注'), align: 'left'},
                        {field: 'createtime', title: __('创建时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'updatetime', title: __('更新时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'operate', title: __('操作'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.initModelManager();
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.initModelManager();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            initModelManager: function () {
                var modelIndex = 1;
                var processList = [];
                
                // 如果是编辑页面，设置正确的初始索引
                if (location.href.indexOf('edit') > -1) {
                    modelIndex = $('.model-item').length;
                }
                
                // 获取工序数据
                var processDataElement = document.getElementById('process-data');
                if (processDataElement && processDataElement.textContent) {
                    try {
                        processList = JSON.parse(processDataElement.textContent);
                    } catch (e) {
                        console.error('JSON解析错误:', e);
                        processList = [];
                    }
                }
                
                // 添加型号
                $(document).on('click', '#add-model', function () {
                    var processHtml = '';
                    for (var i = 0; i < processList.length; i++) {
                        var process = processList[i];
                        processHtml += '<tr>' +
                            '<td>' + process.name + '</td>' +
                            '<td>' +
                                '<input type="number" class="form-control" name="prices[' + process.id + '][' + modelIndex + ']" placeholder="0.00" step="0.01" min="0">' +
                            '</td>' +
                            '<td>' +
                                '<input type="number" class="form-control" name="prices[' + process.id + '_time][' + modelIndex + ']" placeholder="0.00" step="0.01" min="0">' +
                            '</td>' +
                        '</tr>';
                    }
                    
                    var template = '<div class="model-item" data-index="' + modelIndex + '" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 5px;">' +
                        '<h5 style="margin-bottom: 15px; color: #333;">型号信息</h5>' +
                        '<div class="row" style="margin-bottom: 15px;">' +
                            '<div class="col-md-4">' +
                                '<label>型号名称:</label>' +
                                '<input type="text" class="form-control" name="models[' + modelIndex + '][name]" placeholder="请输入型号名称" required>' +
                            '</div>' +
                            '<div class="col-md-3">' +
                                '<label>型号编码:</label>' +
                                '<input type="text" class="form-control" name="models[' + modelIndex + '][model_code]" placeholder="请输入型号编码">' +
                            '</div>' +
                            '<div class="col-md-3">' +
                                '<label>型号描述:</label>' +
                                '<input type="text" class="form-control" name="models[' + modelIndex + '][description]" placeholder="请输入型号描述">' +
                            '</div>' +
                            '<div class="col-md-2">' +
                                '<label>&nbsp;</label><br>' +
                                '<button type="button" class="btn btn-danger btn-sm remove-model">删除</button>' +
                            '</div>' +
                        '</div>' +
                        '<h6 style="margin-bottom: 10px; color: #666;">工序工价设置</h6>' +
                        '<div class="price-table">' +
                            '<table class="table table-bordered table-hover">' +
                                '<thead>' +
                                    '<tr>' +
                                        '<th>工序</th>' +
                                        '<th>计件工价(元/件)</th>' +
                                        '<th>计时工价(元/小时)</th>' +
                                    '</tr>' +
                                '</thead>' +
                                '<tbody>' + processHtml + '</tbody>' +
                            '</table>' +
                        '</div>' +
                    '</div>';
                    
                    $('#model-container').append(template);
                    modelIndex++;
                });
                
                // 删除型号
                $(document).on('click', '.remove-model', function () {
                    if ($('.model-item').length > 1) {
                        $(this).closest('.model-item').remove();
                    } else {
                        Toastr.error('至少需要保留一个型号');
                    }
                });
            }
        }
    };
    return Controller;
}); 